package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ScrollView;

import com.bumptech.glide.Glide;
import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.adapter.MyListAdapter;
import com.lily.aidouzixun.adapter.MyViewHolder;
import com.lily.aidouzixun.bean.DynamicHomeInfo;
import com.lily.aidouzixun.bean.DynamicInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.PullToRefreshView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.MySharedPreferences;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 动态收藏
 */
public class DynamicCollectActivity extends Activity {
    private static final String TAG = "DynamicCollectActivity";

    private TitleBar mTitleBar;
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条
    private ScrollView sv;
    private ListView lvDiscuss;
    private PullToRefreshView pullToRefreshView;
    private static String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle;   //返回标题
    private static final String TITLE = "我的收藏";
    private static MyHandler mHandler;

    private MyListAdapter mListAdapter;
    private List<DynamicInfo> discussList;
    private int action;	//用户行为，1-得到新数据;2-得到更多数据
    private int curPageNum;
    private int totalPageNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discuss_collect_activity);
        init();
        findViews();
        setListeners();
    }

    @Override
    protected void onResume() {
        if (MySharedPreferences.getInstance().getNeedRefreshDynamic(this)) {
            getCollectData(1);
            MySharedPreferences.getInstance().setNeedRefreshDynamic(this, false);
        }
        super.onResume();
    }

    /**
     * 初始化参数
     */
    private void init() {
        action = 1;
        this.key += this.hashCode();
        mActivity = DynamicCollectActivity.this;
        mContext = DynamicCollectActivity.this;
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mActivity);
        mListAdapter = new MyListAdapter(LayoutInflater.from(mContext), MyViewHolder.HolderType.DISCUSS_COLLECT, mContext);
        //清除Glide缓存
        Glide.get(mContext).clearMemory();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(mContext).clearDiskCache();
            }
        }).start();
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        mHandler = new MyHandler(mActivity);
        getCollectData(1);   //得到收藏的信息
    }

    public static MyHandler getMyHandler() {
        return mHandler;
    }
    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);
        pullToRefreshView = (PullToRefreshView) this.findViewById(R.id.refreshable_view);
        pullToRefreshView.setNeedGetMoreData(true);
        pullToRefreshView.setNeedGetNewData(true);
        pullToRefreshView.setFootMode(PullToRefreshView.FootViewMode.ClickAble);
        pullToRefreshView.setOnRefreshListener(refreshListener);
        sv = (ScrollView) this.findViewById(R.id.sv);
        lvDiscuss = (ListView) this.findViewById(R.id.lv_discuss_collect);
        lvDiscuss.setAdapter(mListAdapter);
    }

    /**
     * 显示内容
     * @param discussHomeInfo
     */
    private void showContent(DynamicHomeInfo discussHomeInfo) {

        if (discussHomeInfo == null) {
            mListAdapter.setData(null);
            mListAdapter.notifyDataSetChanged();
            pullToRefreshView.onHeaderRefreshComplete();
            pullToRefreshView.onComplete(false);
            return;
        }
        curPageNum = discussHomeInfo.getCurpage();
        totalPageNum = discussHomeInfo.getTotalpage();
        if (discussList == null || action == 1) {
            discussList = new ArrayList<DynamicInfo>();
        }
        for (int i =0; i<discussHomeInfo.getDiscussList().size(); i++) {
            discussList.add(discussHomeInfo.getDiscussList().get(i));
        }
        if (action == 1) {
            sv.smoothScrollTo(0,0);
            lvDiscuss.setFocusable(false);
        }
        mListAdapter.setData(discussList);
        mListAdapter.notifyDataSetChanged();
        pullToRefreshView.onHeaderRefreshComplete();
        pullToRefreshView.onComplete(false);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //Item监听
        lvDiscuss.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DynamicInfo discussInfo = discussList.get(i);
                if (discussInfo != null) {
                    Intent discussDetailIntent = new Intent(mContext, DynamicDetailActivity.class);
                    discussDetailIntent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
                    discussDetailIntent.putExtra(MyConstant.IntentKey.FROM_TYPE, 2);
                    discussDetailIntent.putExtra(MyConstant.IntentKey.DISCUSSINFO, discussInfo);
                    startActivity(discussDetailIntent);
                }
            }
        });
    }

    /**
     * 从服务端得到信息
     */
    private void getCollectData(int pager) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.DISCUSS_COLLECT);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.DISCUSS_COLLECT);
        param.put(MyConstant.RequireParams.PAGE, pager);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 删除动态
     * @param did
     */
    private void deleteDiscuss(String did) {
        MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.DELETE_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.DELETE_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 点赞
     * @param did
     * @param actionType 操作类型：1：点赞；-1：取消点赞
     */
    public static void support(String did, int actionType) {
        MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.SUPPORT_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.SUPPORT_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.ACTION, actionType);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 收藏
     * @param did
     * @param actionType 操作类型：1：收藏；-1：取消收藏
     */
    public static void collect(String did, int actionType) {
        MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.COLLECT_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.COLLECT_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.ACTION, actionType);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 跳转到登录界面
     */
    public void gotoLoginActivity() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
        startActivityForResult(intent, MyConstant.IntentForResultCODE.LOGIN_REQUESTCODE);
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final DynamicCollectActivity activity = (DynamicCollectActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (mProgressDialog != null) {

                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.DELETE_DISCUSS:   //删除动态
                            String did = (String) msg.obj;
                            activity.deleteDiscuss(did);
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == MyConstant.DataType.DISCUSS_COLLECT) { //收藏
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                if (result != null) {
                                    String errno = (String) result.get(0);
                                    if ("0".equals(errno)) {
                                        DynamicHomeInfo discussHomeInfo = (DynamicHomeInfo) result.get(2);
                                        if (discussHomeInfo != null) {
                                            activity.showContent(discussHomeInfo);
                                        }
                                    } else {
                                        T.shortToast(activity.mActivity, "没有数据！");
                                        activity.showContent(null);
                                    }
                                }
                            } else if (msg.arg1 == MyConstant.DataType.SUPPORT_DISCUSS) {   //点赞
                                SparseArray<Object> supportResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) supportResult.get(0);
                                if ("0".equals(errno)) {    //点赞成功
                                }
                            } else if (msg.arg1 == MyConstant.DataType.COLLECT_DISCUSS) {   //收藏
                                SparseArray<Object> collectResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) collectResult.get(0);
                                if ("0".equals(errno)) {    //收藏成功
                                }
                            } else if (msg.arg1 == MyConstant.DataType.DELETE_DISCUSS) {    //删除
                                SparseArray<Object> deleteDiscussResult = (SparseArray<Object>) msg.obj;
                                if (deleteDiscussResult != null) {
                                    String errno = (String) deleteDiscussResult.get(0);
                                    if ("0".equals(errno)) {
                                        activity.getCollectData(1);
                                    } else {
                                        T.shortToast(activity, "删除失败！");
                                    }
                                }
                            }
                            break;
                        case MessageType.GOTO_LOGIN:   //跳转登录界面
                            activity.gotoLoginActivity();
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
    PullToRefreshView.OnRefreshListener refreshListener = new PullToRefreshView.OnRefreshListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            action = 1;
            getCollectData(1);
        }

        @Override
        public boolean onMore(int nextPageNum) {
            // TODO Auto-generated method stub
            action = 2;
            if(curPageNum < totalPageNum) {
                getCollectData(curPageNum + 1);
                return true;
            } else {
                pullToRefreshView.onComplete(false);
                return false;
            }
        }

        @Override
        public void onGetPageData() {
            // TODO Auto-generated method stub
        }

    };
}
